<template>
  <div class="quality-agent-tree">
    <el-input size="mini"
              v-model.trim="filter"
    >
      <i
        class="el-input__icon el-icon-search"
        slot="suffix"
        @click="filterNode">
      </i>
    </el-input>
      <el-tree-new
        class="el-tree1"
        ref="tree"
        height="280"
        node-key="_id"
        show-checkbox
        :data="optionData"
        accordion
        default-expand-all
        :render-content="renderContent"
        @check-change="checkChange"
        :filter-node-method="filterNode">
      </el-tree-new>
    <el-button @click.stop="save" class="primary_btn fr" type="primary">{{$t('public.save')}}</el-button>
  </div>

</template>
<script>
  import { deepClone, scopeAgents } from '@/utils/m7Utils'
  import tree from '../../../ui-modules/tree/src/tree.vue'
  export default {
    name: 'agentTree',
    components: {
      'el-tree-new': tree
    },
    data () {
      return {
        optionData: [],
        checkedAgents: [],
        filter: ''
      }
    },
    props: {
      readSeat: Array,
      random: Number,
      visable: Boolean
    },
    computed: {
      seatArr () {
        let list = this.readSeat || []
        let arr = list.map((item) => {
          return item._id
        })
        return arr
      }
    },
    watch: {
      filter (val) {
        this.$refs.tree.filter(val)
      },
      seatArr () {
        this.$refs.tree.setCheckedKeys(this.seatArr)
      },
      visable (val) {
        if (val) {
          this.$refs.tree.reset()
        }
      }
    },
    methods: {
      reset () {
        this.$refs.tree.reset()
      },
      save () {
        // 判断是否添加删除坐席
        let checkNode = this.$refs.tree.getCheckedNodes()
        let checkedAgents = checkNode.filter(node => node.type === 'agent').map(node => node._id)

        let arr1 = deepClone(checkedAgents).sort()
        let arr2 = deepClone(this.seatArr).sort()

        let isSame = false
        if (arr1.length === arr2.length) {
          for (let i = 0; i < arr1.length; i++) {
            if (arr1[i] === arr2[i]) {
              isSame = true
            } else {
              isSame = false
              break
            }
          }
        }
        if (!isSame) {
          this.$emit('saveFollowedAgents', checkedAgents)
        }
      },
      checkChange (data, isChecked) {
        if (data.type === 'agent') {
          if (isChecked) {
            this.checkedAgents.push(data._id)
          } else {
            this.checkedAgents = this.checkedAgents.filter(agent => agent !== data._id)
          }
        }
      },
      nodeClick (data, node, self) {
        if (data.type === 'agent' && this.seatArr.indexOf(data._id) === -1) {
//          this.$emit('setFollowedAgents', data._id, 'follow')
        }
      },
      renderContent (h, { node, data, store }) {
        let agentFlag = false
        if ((node.childNodes.length) === 0 && (node.isLeaf === true)) {
          agentFlag = true
        }
        if (this.seatArr.indexOf(data._id) !== -1) {
          return (
            h('span', {
              class: {
                myheader: true,
                floatfl: agentFlag
              }
            }, [
              h('span', {
                domProps: {
                  innerHTML: data.label
                }
              }, [
              ]),
              h('span', {
                domProps: {
                  innerHTML: ' (已选)'
                },
                style: {
                  color: '#459ae9'
                },
                class: {
                  readed: true
                }
              }, [
              ])
            ])
          )
        } else {
          return (
            h('span', {
              class: {
                myheader: true,
                floatfl: agentFlag
              }
            }, [
              h('span', {
                class: {
                  name: true
                },
                domProps: {
                  innerHTML: data.label
                }
              }, [
              ])
            ])
          )
        }
      },
      setDeptAgentCount (obj) {
        if (!obj.children && obj.type === 'agent') {
          return 1
        }

        let count = 0
        for (let i = 0; i < obj.children.length; i++) {
          count += this.setDeptAgentCount(obj.children[i])
        }
        obj.count = count
        obj.label = `${obj.label} (${count})`
        return count
      },
      resetAgent () {
        this.$refs.tree.setCheckedKeys([])
      },
      setCheckedKeys () {
//        this.checkedAgents = deepClone(this.seatArr) || []
        this.filter = ''
        this.$refs.tree.setCheckedKeys(this.seatArr)
      },
      deleteAgent (key) {
        this.$refs.tree.setChecked(key, false)
      },
      filterNode (value, data) {
        if (!value) return true
        return data.type === 'agent' && (data.label.indexOf(value) !== -1 || data.pinyin.indexOf(value) !== -1)
      },
      handleData () {
        Promise.all([
          this.$store.dispatch('getCache', { type: 'depts' }),
          this.$store.dispatch('getCache', { type: 'agents' })
        ]).then(([depts, agents]) => {
          let optionData = []
          let agentQc = scopeAgents('qc', agents)
          dealDept(depts, optionData, '')
          dealAgent(agentQc, optionData[0].children)
          let noDeptAgents = agentQc.filter(agent => agent.status === 'enable' && !agent.deptId).map(agent => ({ _id: agent._id, count: 0, type: 'agent', label: `${agent.displayName} ${agent.exten}`, pinyin: agent.pinyin }))
          optionData[0].children.push(...noDeptAgents)
          this.setDeptAgentCount(optionData[0])
          console.log(optionData)
          this.optionData = optionData
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys(this.seatArr)
          })
//          this.$on('resetAgent', () => {
//            this.resetAgent()
//          })
//          this.$on('deleteAgent', (_id) => {
//            this.deleteAgent(_id)
//          })
//          if (this.agentCheckedIds.length > 0) {
//            this.setCheckedAgent(this.agentCheckedIds)
//          }
        })
      },
      filterExten (agents) {
        let result = []
        let hash = {}
        agents.forEach(function (ele) {
          if (!hash[ele._id]) {
            result.push(ele)
            hash[ele._id] = true
          }
        })
        return result
      }
    },
    beforeMount () {
      this.handleData()
    }
  }
  function dealDept (depts, arr, key) {
    for (let i = 0; i < depts.length; i++) {
      let dept = depts[i]
      if (dept.pId === key) {
        let obj = {
          _id: dept._id,
          type: 'dept',
          label: dept.name,
          order: dept.order,
          children: []
        }
        arr.push(obj)
        dealDept(depts, obj.children, dept._id)
      }
    }
  }
  function dealAgent (agents, arr) {
    if (!arr) {
      return
    }
    for (let i = 0; i < arr.length; i++) {
      dealAgent(agents, arr[i].children)
      let deptAgents = agents.filter(agent => agent.status === 'enable' && agent.deptId === arr[i]._id)
      deptAgents = deptAgents.map(agent => ({ _id: agent._id, type: 'agent', label: `${agent.displayName} ${agent.exten}`, pinyin: agent.pinyin }))
      arr[i].children.push(...deptAgents)
    }
  }
//  function fliterDept (optionData) {
//    if (optionData.type === 'dept') {
//      let i = optionData.children.length - 1
//      while (i >= 0) {
//        if (optionData.children[i].type === 'dept' && (optionData.children[i].count === 0)) {
//          optionData.children.splice(i, 1)
//        } else if (optionData.children[i].type === 'dept' && (optionData.children[i].count !== 0)) {
//          fliterDept(optionData.children[i])
//        }
//        i--
//      }
//    }
//  }
</script>
<style lang="stylus">
  .quality-agent-tree .el-tree1 .el-tree-node >.el-tree-node__children
    overflow visible
</style>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .el-checkbox
    padding-right 0
  .el-tree1
    padding-bottom 5px
    max-height 280px
    overflow auto
    border none
</style>
